import type { ProcessBlock, BlockProcessor, PreBlock, PreParagraph, Row } from '../types';
import { isEmptyRow } from '../util';

const isBlockBegin = (row: Row) => false;

/**
 * ```
 *                                 result.push(block | empty row)
 *        +--------------------------+
 *       /                            \
 *      /                              \  <empty row or block>
 *     /                                \
 *    V         <non-empty row>          \
 * INIT(0) --------------------------> PARAGRAPH(1)
 * ^   \                   result.push(p) ^    \
 *  \   \                                  \    \
 *   \   \ <empty row or block>             \    \ <non-empty row>
 *    \   \                                  \    \
 *     \   V                                  \    V
 *  result.push(block | empty row)          result.last.rows.push(block)
 * ```
 */
const processBlock: ProcessBlock = (pbs) => {
  const result: PreBlock[] = [];
  let state = 0;

  for (const block of pbs) {
    const { type } = block;
    switch (state) {
      case 0: {
        if (type == 'row') {
          if (isEmptyRow(block)) {
            result.push({ type: 'br', row: block });
          } else {
            result.push({ type: 'paragraph', rows: [block] });
            state = 1;
          }
        } else {
          result.push(block);
        }
        break;
      }
      case 1: {
        if (type == 'row') {
          if (isEmptyRow(block)) {
            result.push({ type: 'br', row: block });
            state = 0;
          } else {
            (result[result.length - 1] as PreParagraph).rows.push(block);
          }
        } else {
          result.push(block);
          state = 0;
        }
        break;
      }
    }
  }

  return result;
};

const paragraphProcessor: BlockProcessor = {
  isBlockBegin,
  process: processBlock,
};

export default {
  processor: paragraphProcessor,
};
